﻿using System;
using System.Web;
using System.Web.Mvc;
using SuperiorCommon;
using SuperiorModel;
using SuperiorShopBussinessService;
using System.Text;
using Newtonsoft.Json.Linq;
using WxPayAPIMobileShopCode.Common.Helpers;

namespace H5.SuperiorShop.Controllers
{
    [JsonException]
    public class ServiceShopController : BaseController
    {
        private readonly IShopService _IShopService;

        public ServiceShopController(IShopService IShopService)
        {
            _IShopService = IShopService;
        }
        protected override void Dispose(bool disposin)
        {
            this._IShopService.Dispose();
            base.Dispose(disposin);
        }
        // GET: ServiceShop
        [CheckShopLoginFitler]
        public ActionResult Index()
        {
            var shop = Session[SessionKey.ServiceShopKey] as ShopInfoModel;
            ViewBag.Amount = shop.CanUserAmount;

            ViewBag.ShowPhone = ToolManager.SecretPhone(shop.PhoneNumber);
            ViewBag.HidePhone = shop.PhoneNumber;
            return View();
        }



        public ActionResult Login()
        {
            return View();
        }

        /// <summary>
        /// 登录验证码
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public FileContentResult CaptchaImage()
        {
            var captcha = new LiteralCaptcha(115, 48, 4);
            var bytes = captcha.Generate();
            Session["captcha"] = captcha.Captcha;
            return new FileContentResult(bytes, "image/jpeg");
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [AjaxOnly]
        [HttpPost]
        public JsonResult Login(ShopLoginParams model)
        {
            if (!ModelState.IsValid)
                return Error(base.ErrorMsg());
            var captcha = Session["captcha"];
            if (captcha == null)
                return Error("验证码错误");
            string strcaptcha = Convert.ToString(captcha);
            if (strcaptcha != model.Code)
                return Error("验证码错误");
            //查询商城数据
            var shop = _IShopService.GetShopModel(model.UserName, MD5Manager.MD5Encrypt(model.PassWord));
            if (string.IsNullOrEmpty(shop.Id))
                return Error("账号或密码错误");
            if (shop.OptionStatus == 2)
                return Error("账号已被冻结");
            if (shop.OptionStatus == 0)
                return Error("账号审核中");
            shop.ShopAdminType = 1;
            SessionManager.SetSession(SessionKey.ServiceShopKey, shop,"", 20);
            return Success(true);
        }
        /// <summary>
        /// 获取短信验证码
        /// </summary>
        /// <returns></returns>
        [AjaxOnly]
        [CheckShopLoginFitler]
        public JsonResult GetCode()
        {
            var shop = Session[SessionKey.ServiceShopKey] as ShopInfoModel;
            var phone = shop.PhoneNumber;
            var code = new Random().Next(100000, 999999).ToString();
            //var code = "111111";//测试放开
            Redis.RedisManager.Set<string>(phone + code, code, DateTime.Now.AddMinutes(5));
            var res =  Aly.Sms.SmsManager.Instance.Send(phone, code);
            if (res != 200)
                return Error("发送失败");
            return Success(true);
        }
        /// <summary>
        /// 提交提现
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [CheckShopLoginFitler]
        [AjaxOnly]
        [HttpPost]
        public JsonResult SubmitAmount(Shop_SubmitAmountParms model)
        {
            if (!ModelState.IsValid)
                return Error(base.ErrorMsg());
            if (model.Amount == 0)
                return Error("提现金额必须大于0");
            var shop = Session[SessionKey.ServiceShopKey] as ShopInfoModel;
            //验证验证码
            var _code = Redis.RedisManager.Get<string>(shop.PhoneNumber + model.Code);
            if (_code != model.Code)
                return Error("请输入正确的验证码");
            //系统下单
            string msg = "";
            var orderno = ToolManager.CreateNo();
            var shopAdminId = SecretClass.DecryptQueryString(shop.Id).ToInt();
            var requestModel = _IShopService.ShopCashOutAmount(shopAdminId,model.Amount,orderno,out msg);
            if (msg!="")
                return Error(msg);

            //var ret = RequestWxCashOut(orderno,requestModel.OpenId,model.Amount);
            //var status = ret ? 1 : 2;
            ////异步更新此订单状态
            //Task.Factory.StartNew(() =>
            //{
            //    _IShopService.UpdateShopCashCoutOder(orderno,status);
            //});
            return Success(requestModel.ExpressAmount);
        }

        private bool RequestWxCashOut(string orderno,string openid,decimal amount)
        {
            var res = true;
            //微信企业付款
            var url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
            WxPayData data = new WxPayData();
            data.SetValue("mch_appid", ConfigSettings.Instance.APPID);//公众账号ID
            data.SetValue("mchid", ConfigSettings.Instance.Merchant_Id);//商户号
            data.SetValue("nonce_str", ToolManager.GenerateNonceStr());//随机字符串
            data.SetValue("partner_trade_no", orderno);
            data.SetValue("openid", openid);
            data.SetValue("check_name", "NO_CHECK");
            data.SetValue("amount", (int)Math.Round(amount * 100));//总金额 单位分
            data.SetValue("desc", "超奇科技向用户" + openid + "付款");
            data.SetValue("spbill_create_ip", Net.Ip);//终端ip
            data.SetValue("sign", data.MakeSign(ConfigSettings.Instance.PaySecret));
            string xml = data.ToXml();
            string response = WeiXinHelper.Post(xml, url, true, 10);
            LogManger.Instance.WriteLog("企业微信付款请求返回:"+response);
            WxPayData result = new WxPayData();
            result.FromXml(response);
            //签名验证
            // 错误时没有签名
            if (result.IsSet("return_code") && result.GetValue("return_code").ToString() == "SUCCESS")
            {
                //请求成功
                if (result.GetValue("result_code").ToString() == "SUCCESS")
                {
                    //说明转账一定成功了
                    res = true;
                }
                else
                {
                    res = false;//不一定是失败，系统暂时定为失败，后台工作人员人工操作时，先查询微信商户系统确认，再手工微信转账
                }

            }
            else
            {
                if (result.IsSet("return_msg") && result.GetValue("return_msg").ToString() != "")
                {
                    LogManger.Instance.WriteLog("订单号：" + orderno + ";企业微信付款失败：" + result.GetValue("return_msg").ToString());
                    res = false;
                }
                else
                {
                    res= false;
                }
            }
            return res;
        }

        public ActionResult ShopWxLogin()
        {
            string code = Request["code"];
            string state = Request["state"];
            var appid = ConfigSettings.Instance.APPID;
            var secret = ConfigSettings.Instance.APP_Secret;
            if (!string.IsNullOrEmpty(code) && !string.IsNullOrEmpty(state))
            {
                int said = 0;
                if (!int.TryParse(SecretClass.DecryptQueryString(state), out said))
                {
                }
                if (said == 0)
                {
                    Response.Redirect("/Error/Index?msg=" + HttpUtility.UrlEncode("请不要随意改变网站参数", Encoding.UTF8));
                    return new EmptyResult();
                }
                //通过code换取网页授权access_token
                string tokens = WeiXinHelper.GetToken(appid, secret, code);
                try
                {
                    JObject jo = JObject.Parse(tokens);
                    string openid = jo["openid"].ToString();
                    string access_token = jo["access_token"].ToString();

                    if (!string.IsNullOrEmpty(openid) && !string.IsNullOrEmpty(access_token))
                    {
                        LogManger.Instance.WriteLog("openid:" + openid + "-------token:" + access_token);
                        //读取用户最新信息
                        string jsonstr = WeiXinHelper.GetUserInfo(access_token, openid);
                        LogManger.Instance.WriteLog("获取USERiNFO" + jsonstr);
                        Newtonsoft.Json.Linq.JObject joUser = Newtonsoft.Json.Linq.JObject.Parse(jsonstr);

                        var headImgUrl = joUser["headimgurl"].ToString();
                        var nickName = joUser["nickname"].ToString();
                        
                        //更新回shopAdmin
                        _IShopService.UpdateShopAdmin(openid,nickName,headImgUrl,said);
                        Response.Redirect("/ServiceShop/Index", false);
                        return new EmptyResult();
                    }
                    else
                    {
                        Response.Redirect("/Error/Index?msg=" + HttpUtility.UrlEncode("获取微信信息失败", Encoding.UTF8));
                        return new EmptyResult();
                    }
                }
                catch (Exception ex)
                {
                    LogManger.Instance.WriteLog("获取获取access_token异常:" + ex.ToString());
                    Response.Redirect("/Error/Index?msg=" + HttpUtility.UrlEncode("获取access_token异常", Encoding.UTF8));
                    return new EmptyResult();
                }

            }
            else
            {
                var shopModel = Session[SessionKey.ServiceShopKey] as ShopInfoModel;
                if (shopModel == null)
                {
                    Response.Redirect("/Error/Index?msg=" + HttpUtility.UrlEncode("尝试微信登录时,火球店铺模型为空", Encoding.UTF8));
                    return new EmptyResult();
                }
                //发起请求
                var redirect = ConfigSettings.Instance.WebHost + "ServiceShop/ShopWxLogin";
                string url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + HttpUtility.UrlEncode(redirect, Encoding.UTF8) + "&response_type=code&scope=snsapi_userinfo&state=" + shopModel.Id + "#wechat_redirect";
                Response.Redirect(url);
                return new EmptyResult();
            }
        }
    }
}